package com.meij.activity.user;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.DatePicker;
import android.widget.EditText;

import com.anno.ActionBarSet;
import com.anno.ActionBarSet.WAY;
import com.meij.MJApplaction;
import com.meij.R;
import com.meij.activity.MjActivity;
import com.meij.bean.UserInfo;
import com.meij.http.Json;
import com.meij.http.MJNetCallBack;
import com.meij.http.Url;
import com.meij.util.Info;
import com.util.DateUtils;
import com.util.FileUtils;

@ActionBarSet(title = "完善信息", way = WAY.TITLE, homeAsUpEnabled = true)
public class UpdateActivity extends MjActivity {
	// 1图库 2拍照 3完成后的返回结果
	private final int CHOICEPHOTO = 1, TAKEPHOTO = 2, PHOTORESOULT = 3;
	private final String IMAGE_UNSPECIFIED = "image/*";
	private final String[] photos = new String[] { "图库", "拍照" };
	private File file;
	private String birthday, province, city, place, profile;
	private EditText edite1;
	private final String[] provinces = new String[] { "临时省1", "临时省2", "临时省3", "临时省4" };
	private final String[] citys = new String[] { "临时市1", "临时市2", "临时市3", "临时市4" };
	private final String[] places = new String[] { "临时地点1", "临时地点2", "临时地点3", "临时地点4" };
	// 摇晃提示动画
	private Animation shake;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_update);
		actionBar.setDisplayHomeAsUpEnabled(true);
		edite1 = (EditText) findViewById(R.id.editText1);
		shake = AnimationUtils.loadAnimation(this, R.anim.shake);
		setInfo();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK || data == null) {
			return;
		}
		Bitmap photo;
		switch (requestCode) {
		case CHOICEPHOTO:
			Uri uri = data.getData();
			try {
				ContentResolver resolver = getContentResolver();
				photo = Media.getBitmap(resolver, uri);
				zoomPic(photo);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			break;
		case TAKEPHOTO:
			photo = data.getExtras().getParcelable("data");
			zoomPic(photo);
			break;
		case PHOTORESOULT:
			photo = data.getExtras().getParcelable("data");
			FileUtils.saveBitmapToFile(photo, "/temp.jpg");
			file = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
			aq.id(R.id.imageView1).image(photo);
			break;
		}
	}

	/***
	 * 设置初始值
	 */
	private void setInfo() {
		UserInfo userInfo = MJApplaction.userInfo;
		birthday = userInfo.getPerson().getBirthday();
		province = userInfo.getPerson().getProvince();
		city = userInfo.getPerson().getCity();
		place = userInfo.getPerson().getBilliard_hall_love();
		profile = userInfo.getPerson().getProfile();
		aq.id(R.id.imageView1).image(Url.ctx + userInfo.getPerson().getAvatar());
		aq.id(R.id.textView2).text(birthday);
		aq.id(R.id.textView3).text(province);
		aq.id(R.id.textView4).text(city);
		aq.id(R.id.textView5).text(place);
		aq.id(R.id.editText1).text(profile);
	}

	/***
	 * 缩放图片
	 * 
	 * @param photo
	 */
	private void zoomPic(Bitmap photo) {
		FileUtils.saveBitmapToFile(photo, "/temp.jpg");
		File tempFile = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
		startPhotoZoom(Uri.fromFile(tempFile));
	}

	public void setAvatar(View view) {
		Builder builder = new Builder(this);
		builder.setItems(photos, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case 0:
					choicephoto();
					break;
				case 1:
					takephoto();
					break;
				}
			}
		});
		builder.show();
	}

	public void setBirth(View view) {
		DatePickerDialog date = new DatePickerDialog(this, new OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
				Calendar calendar = new GregorianCalendar(year, monthOfYear, dayOfMonth);
				birthday = DateUtils.parseDate2(calendar.getTime().getTime());
				aq.id(R.id.textView2).text(birthday);
			}
		}, 1990, 0, 1);
		date.show();
	}

	public void setProvince(View view) {
		Builder builder = new Builder(this);
		builder.setItems(provinces, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				province = provinces[which];
				aq.id(R.id.textView3).text(province);
			}
		});
		builder.show();
	}

	public void setCity(View view) {
		Builder builder = new Builder(this);
		builder.setItems(citys, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				city = citys[which];
				aq.id(R.id.textView4).text(city);
			}
		});
		builder.show();
	}

	public void setPlace(View view) {
		Builder builder = new Builder(this);
		builder.setItems(places, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				place = places[which];
				aq.id(R.id.textView5).text(place);
			}
		});
		builder.show();
	}

	/***
	 * 信息校验
	 * 
	 * @return
	 */
	private boolean checkInfo() {
		if (file == null) {
			setAvatar(null);
			Toast(R.string.update_avatar);
			return false;
		}
		if (TextUtils.isEmpty(birthday)) {
			setBirth(null);
			Toast(R.string.update_birthday);
			return false;
		}
		if (TextUtils.isEmpty(province)) {
			setProvince(null);
			Toast(R.string.update_city);
			return false;
		}
		if (TextUtils.isEmpty(city)) {
			setCity(null);
			Toast(R.string.update_city);
			return false;
		}
		if (TextUtils.isEmpty(place)) {
			setPlace(null);
			Toast(R.string.update_place);
			return false;
		}
		profile = edite1.getText().toString();
		if (TextUtils.isEmpty(profile)) {
			Toast(R.string.update_introduce);
			edite1.requestFocus();
			edite1.startAnimation(shake);
		}
		return true;
	}

	public void submit(View view) {
		if (checkInfo()) {
			String url = Url.upinfo;
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("userkey", MJApplaction.userInfo.getUserkey());
			if (!TextUtils.isEmpty(birthday)) {
				params.put("birthday", birthday);
			}
			if (file != null) {
				params.put("avatar", file);
			}
			if (!TextUtils.isEmpty(province)) {
				params.put("province", province);
			}
			if (!TextUtils.isEmpty(city)) {
				params.put("city", city);
			}
			if (!TextUtils.isEmpty(place)) {
				params.put("billiardHallLove", place);
			}
			if (!TextUtils.isEmpty(profile)) {
				params.put("profile", profile);
			}
			MJNetCallBack callBack = new MJNetCallBack(this) {
				@Override
				public void onSuccess(JSONObject object) {
					super.onSuccess(object);
					UserInfo userInfo = Json.getUserInfo(object);
					MJApplaction.userInfo.setUserkey(userInfo.getUserkey());
					MJApplaction.userInfo.getPerson().setBirthday(birthday);
					MJApplaction.userInfo.getPerson().setProvince(province);
					MJApplaction.userInfo.getPerson().setCity(city);
					MJApplaction.userInfo.getPerson().setBilliard_hall_love(place);
					MJApplaction.userInfo.getPerson().setProfile(profile);
					Info.saveUserInfo(UpdateActivity.this);
					Toast("修改成功");
					finish();
				}
			};
			postJson(url, params, callBack);
		}
	}

	/***
	 * 图库选择
	 */
	public void choicephoto() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			Intent intent = new Intent();
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(intent, CHOICEPHOTO);
		} else {
			Toast("请先插入SD卡");
		}
	}

	/***
	 * 拍照
	 */
	public void takephoto() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			startActivityForResult(intent, TAKEPHOTO);
		} else {
			Toast("请先插入SD卡");
		}
	}

	/***
	 * 裁剪图片页面
	 */
	private void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("outputX", 400);// 输出图片大小
		intent.putExtra("outputY", 400);
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, PHOTORESOULT);
	}
}
